import { HTMLProps, useContext } from 'react';

import { useCreateOrderModal } from '@/entities/course';
import { innerUrls } from '@/shared/constants';
import { ModalContext } from '@/shared/context/ModalContext';
import { ReactComponent as Badge } from '@/shared/icons/Badge.svg';
import { Modals } from '@/shared/interfaces';
import { getImageUrl } from '@/shared/lib';
import { Button, RatingTag } from '@/shared/ui';
import Image from 'next/image';

import cs from './CourseCard.module.scss';

interface Props {
  id: number;
  title: string;
  image?: string;
  rate?: number;
  price: number;
  discount?: number;
  discountPrice?: number;
  isTip?: boolean;
  isAdvertising?: boolean;
  priority?: boolean;
  target?: HTMLProps<HTMLAnchorElement>['target'];
}

export const CourseCard = ({
  id,
  rate,
  title,
  price,
  discountPrice,
  discount,
  image,
  isTip,
  isAdvertising,
  priority,
  target,
}: Props) => {
  const { handleBuy } = useCreateOrderModal(id);

  const actualPrice = (discountPrice !== null ? discountPrice : price)?.toLocaleString();
  const isDiscount = price !== null && Number(discount) > 0 && discountPrice !== null;
  return (
    <div className={cs.card}>
      <Button className={cs.course} href={innerUrls.course(id)} link target={target}>
        <div className={cs.image}>
          {rate && (
            <div className={cs.tag}>
              <RatingTag isCard={isTip} value={rate} />
            </div>
          )}
          <Image
            alt="Обложка курса"
            fill
            priority={priority}
            sizes="(max-width: 768px) 50vw, (max-width: 1024px) 33vw, (max-width: 1366px) 20vw, 15vw"
            src={getImageUrl(image)}
          />
          {isAdvertising && <Badge className={cs.badge} />}
        </div>
        <p className={cs.title}>{title}</p>
      </Button>

      {isDiscount && <p className={cs.discount}>Скидка {discount}%</p>}
      <div className={cs.price}>
        <Button
          aria-label={`Купить за ${actualPrice} ₽`}
          className={cs.price_actual}
          data-testid={`button-modal-buy-${id}`}
          onClick={handleBuy}
        >
          {actualPrice}&nbsp;₽
        </Button>
        {isDiscount && <div className={cs.price_old}>{price?.toLocaleString()}&nbsp;₽</div>}
      </div>
    </div>
  );
};
